package com.alibaba.citrus.cr.forecast.facade.service;

import com.alibaba.citrus.cr.common.annotation.ProcessInvoker;
import com.alibaba.citrus.cr.forecast.repository.ForecastOrderLineQueryRepository;
import com.alibaba.citrus.cr.forecast.repository.ForecastOrderQueryRepository;
import com.alibaba.cz.base.tool.Nullable;
import com.alibaba.cz.base.tool.log.Log;
import com.alibaba.cz.base.tool.page.PageResult;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.lattice2.epoch.middleware.mq.runtime.EpochMessageService;
import com.alibaba.lattice2.epoch.sdk.model.Result;
import com.alibaba.nacos.common.utils.MapUtils;
import com.epoch.app.crb2btradecenter.api.orderquery.service.OrderQueryService;
import com.epoch.app.crb2btradecenter.dto.response.OrderPageQueryResponse;
import com.epoch.app.crb2btradecenter.model.dto.PageQueryOrderEsListRequest;
import com.epoch.app.crforecastsales.api.forecastorderwrite.service.ForecastOrderWriteService;
import com.epoch.app.crforecastsales.createforecastorderrecords.dto.*;
import com.epoch.app.crforecastsales.createforecastorderrecords.model.CreateForecastOrderRecords;
import com.epoch.app.crforecastsales.createforecastorderrecords.service.CreateForecastOrderRecordsService;
import com.epoch.app.crforecastsales.domian.deallinequeue.dto.LoadDealLineQueueListRequest;
import com.epoch.app.crforecastsales.domian.deallinequeue.model.DealLineQueue;
import com.epoch.app.crforecastsales.domian.deallinequeue.service.DealLineQueueService;
import com.epoch.app.crforecastsales.domian.forecastorderline.model.ForecastOrderLine;
import com.epoch.app.crforecastsales.domian.forecastorderline.service.ForecastOrderLineService;
import com.epoch.app.crforecastsales.dto.request.BatchAnalysisOrdersRequest;
import com.epoch.app.crforecastsales.enums.AnalyzeReasonsSEO;
import com.epoch.app.crforecastsales.model.dto.BatchSaveOrderConfirmRequest;
import com.epoch.app.crforecastsales.model.dto.BatchSaveOrderConfirmResponse;
import com.epoch.app.crforecastsales.model.dto.ForecastOrderOutResponse;
import com.epoch.app.crforecastsales.model.dto.QuerySaleOrderOutRep;
import com.epoch.app.crforecastsales.model.enums.CreateForecastOrderRecoudStatusSEO;
import com.epoch.app.crforecastsales.model.enums.ForecastDealStatusSEO;
import com.epoch.app.crforecastsales.sdo.ForecastOrderLineSDO;
import com.epoch.app.crforecastsales.sdo.ForecastOrderSDO;
import com.epoch.app.crforecastsales.service.CrForecastSalesService;
import com.epoch.app.crplatformenhance.model.dto.ApiContext;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.compress.utils.Lists;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.*;

/**
 * 说明
 * 通用需求接入中台-创建预报单并分析生成销售单
 *
 * @author jc
 * @since 1.0
 */
@Service
@Primary
public class CreateForecastOrderRecordsServiceImpl implements CreateForecastOrderRecordsService {

    private static final Log log = Log.getLogger(CreateForecastOrderRecordsServiceImpl.class);

    @Autowired
    private ForecastOrderLineQueryRepository forecastOrderLineQueryRepository;

    @Autowired
    private ForecastOrderWriteService forecastOrderWriteService;

    @Autowired
    private CrForecastSalesService otsForecastSalesService;

    @Autowired
    private EpochMessageService messageService;

    @Autowired
    private DealLineQueueService dealLineQueueService;

    @Autowired
    private ForecastOrderQueryRepository forecastOrderQueryRepository;

    @Autowired
    private OrderQueryService orderQueryService;

    @Autowired
    private ForecastOrderLineService forecastOrderLineService;

    public static final String FORECASTORDERBIZIDS = "forecastOrderBizIds";
    public static final String TETONGEMPLOYEEID = "Tetong";
    public static final String TETONGEMPLOYEENAME = "特通";


    /**
     * 说明
     * mq1-consumer-api
     * 接受mq1消息，根据预报单主单号查子单集合，并记录到record表，将创建成功的预报单，以单个主单的维度将子单集合分析并发mq2
     * 接口一：第二步（内部调第三步）
     *
     * @author jc
     * @since 1.0
     */
    @Override
    @ProcessInvoker
    public Result<Boolean> recordCreateOrder(RecordCreateOrderRequest recordCreateOrderRequest) {
        if (Objects.isNull(recordCreateOrderRequest)) {
            return Result.fail("SYS_ERR_ANY_INVALID_PARAM", "系统异常，消息内容为空");
        }
        String message = recordCreateOrderRequest.getMessage();

        if (StringUtils.isBlank(message)) {
            return Result.fail("SYS_ERR_ANY_INVALID_MSG", "系统异常，项目内容为空");
        }

        List<String> forecastOrderIds = null;
        try {
            JSONObject jsonObject = JSONObject.parseObject(message);
            // 消息转换
            forecastOrderIds = Optional.ofNullable(jsonObject.getJSONArray(FORECASTORDERBIZIDS).toJavaList(String.class)).orElse(Lists.newArrayList());
            log.info("prepare start sync analysis forecastOrder,forecastOrderBizNos:" + JSON.toJSONString(forecastOrderIds));
        } catch (Exception e) {
            log.error("Parse message failed:" + e.getMessage(), e);
        }

        // 记录record
        Objects.requireNonNull(forecastOrderIds).forEach(forecastOrderId -> {
            log.info("create forecastOrder step two"  + forecastOrderId);
            CreateForecastOrderRecords record = new CreateForecastOrderRecords();
            //查预报单明细
            ForecastOrderLine forecastOrderLine = new ForecastOrderLine();
//            SearchForecastOrderRequest searchForecastOrderRequest = new SearchForecastOrderRequest();
            forecastOrderLine.setMainOrderBizId(forecastOrderId);
            Result<List<ForecastOrderLine>> listResult = forecastOrderLineService.loadForecastOrderLineList(forecastOrderLine);
            List<String> orderLineIds = new ArrayList<>();
            Nullable.stream(listResult.getResult()).forEach(rep -> orderLineIds.add(String.valueOf(rep.getId())));
            //record预报单业务ID，子单id集合，Status处理状态(0:处理中，1:已完成)，DealStatus(0:待处理,1:分析中,2:分析完成,7:分析失败)，失败原因(货品编码：失败原因；+++)，创建时间，重试次数，更新时间，版本号
            // 处理状态为已完成，分析状态为2/7
            record.setOrderBizId(forecastOrderId);
            record.setOrderLineBizIds(orderLineIds);
            record.setStatus(CreateForecastOrderRecoudStatusSEO.Processing.getValue());
            record.setDealStatus(ForecastDealStatusSEO.WAITING_DEAL.getStatus());
            //record.setFailReason("");
            record.setGmt_create(System.currentTimeMillis());
            record.setGmt_modified(System.currentTimeMillis());
            record.setRetryNum(0);
            record.setVersion(1);//版本号初始值：1，每次更新自动+1
            this.createOneRecord(record);
            //将创建完的预报单分析并发mq2
            try {
                this.analysisOrderLineAndSendMsg(AnalysisOrderLineAndSendMsgRequest.builder().forecastOrderLineIds(orderLineIds).build());
            } catch (Exception e) {//放入分析队列失败，更新记录表
                record = this.loadOneRecord(LoadOneRecordRequest.builder().orderBizId(record.getOrderBizId()).build());
                record.setFailReason(JSON.toJSONString(new JSONObject().put("Exception", "放入分析队列失败")));
                record.setGmt_modified(System.currentTimeMillis());
                this.updateOneRecord(record);
                log.error("放入分析队列失败{}", e.getMessage());
            }
        });

        return Result.success(true);

    }


    @Override
    public Result<List<QuerySaleOrderOutRep>> querySalesOrderByForecastOrderNo(QuerySalesOrderByForecastOrderNoRequest querySalesOrderByForecastOrderNoRequest) {
        List<QuerySaleOrderOutRep> responseList = new ArrayList<>();
        Result<List<QuerySaleOrderOutRep>> result = new Result<>();

        if (Objects.isNull(querySalesOrderByForecastOrderNoRequest)) {
            result.setMessage("系统错误，参数异常！");
            result.setSuccess(false);
            return result;
        }
        if (CollectionUtils.isEmpty(querySalesOrderByForecastOrderNoRequest.getForecastOrderBizNos())) {
            result.setMessage("请填写预报单");
            result.setSuccess(false);
            return result;
        }
        List<String> forecastOrderBizNos = querySalesOrderByForecastOrderNoRequest.getForecastOrderBizNos();
        // 查销售单OrderQuery$pageQueryOrderListES 查不到跳过 查到了再查记录表
        forecastOrderBizNos.forEach(forecastOrderBizNo -> {
            PageQueryOrderEsListRequest pageQueryOrderEsListRequest = new PageQueryOrderEsListRequest();
            pageQueryOrderEsListRequest.setFrontOrderBizId(forecastOrderBizNo);
            Result<List<OrderPageQueryResponse>> listResult = orderQueryService.pageQueryOrderListES(pageQueryOrderEsListRequest);
            if (Objects.nonNull(listResult) &&  CollectionUtils.isNotEmpty(listResult.getResult())) {//查记录表
                LoadOneRecordRequest recordRequest = new LoadOneRecordRequest();
                recordRequest.setOrderBizId(forecastOrderBizNo);
                CreateForecastOrderRecords record = this.loadOneRecord(recordRequest);
                if (!ObjectUtils.isEmpty(record)) {
                    boolean complete = CreateForecastOrderRecoudStatusSEO.done.getValue().equals(record.getStatus());
                    OrderPageQueryResponse orderPageQueryResponse = listResult.getResult().get(0);
                    QuerySaleOrderOutRep rep = new QuerySaleOrderOutRep();
                    rep.setOrderBizId(orderPageQueryResponse.getOrderBizId());
                    rep.setOrderOutId(orderPageQueryResponse.getOuterId());
                    rep.setForecastOrderBizNo(forecastOrderBizNo);
                    rep.setComplete(complete);
                    rep.setMessage(complete?"处理成功":JSONObject.toJSONString(record.getFailReason()));
                    responseList.add(rep);
                }else {// 未查到记录表，只返回预报单号
                    QuerySaleOrderOutRep rep = new QuerySaleOrderOutRep();
                    rep.setForecastOrderBizNo(forecastOrderBizNo);
                    responseList.add(rep);
                }
            } else {// 未查到销售单，查记录表，返回错误信息
                LoadOneRecordRequest recordRequest = new LoadOneRecordRequest();
                recordRequest.setOrderBizId(forecastOrderBizNo);
                CreateForecastOrderRecords record = this.loadOneRecord(recordRequest);
                if (!ObjectUtils.isEmpty(record)) {
                    boolean complete = CreateForecastOrderRecoudStatusSEO.done.getValue().equals(record.getStatus());
//                    OrderPageQueryResponse orderPageQueryResponse = listResult.getResult().get(0);
                    QuerySaleOrderOutRep rep = new QuerySaleOrderOutRep();
//                    rep.setOrderBizId(orderPageQueryResponse.getOrderBizId());
//                    rep.setOrderOutId(orderPageQueryResponse.getOuterId());
                    rep.setForecastOrderBizNo(forecastOrderBizNo);
                    rep.setComplete(complete);
                    rep.setMessage(record.getFailReason() == null? "":JSONObject.toJSONString(record.getFailReason()));
                    responseList.add(rep);
                }else {// 未查到记录表，只返回预报单号
                    QuerySaleOrderOutRep rep = new QuerySaleOrderOutRep();
                    rep.setForecastOrderBizNo(forecastOrderBizNo);
                    responseList.add(rep);
                }
            }
        });

        result.setResult(responseList);
        result.setSuccess(Boolean.TRUE);
        result.setTotal(responseList.size());
        return result;
    }

    /**
     * 说明
     * 接受预报主单id查记录表，过滤处理状态为已完成且分析状态为分析失败的预报单，调分析方法再分析发mq2
     * 接口二：第一步（内部调用第二步）
     *
     * @author jc
     * @since 1.0
     */
    @Override
    @ProcessInvoker
    public Result<List<ForecastOrderOutResponse>> getNeedRetryForecastOrdersByRecord(GetNeedRetryForecastOrdersByRecordRequest getNeedRetryForecastOrdersByRecordRequest) {

        List<ForecastOrderOutResponse> responseList = new ArrayList<>();
        Result<List<ForecastOrderOutResponse>> result = new Result<>();

        if (Objects.isNull(getNeedRetryForecastOrdersByRecordRequest)) {
            result.setMessage("系统错误，参数异常！");
            result.setSuccess(false);
            return result;
        }
        if (CollectionUtils.isEmpty(getNeedRetryForecastOrdersByRecordRequest.getForecastOrderBizNos()) || StringUtils.isEmpty(getNeedRetryForecastOrdersByRecordRequest.getBizCode())) {
            result.setMessage("请填写预报单或业务编码");
            result.setSuccess(false);
            return result;
        }

        log.info("retry create ForecastOrders" + JSONObject.toJSONString(getNeedRetryForecastOrdersByRecordRequest));
        //分页查预报单创建记录表
        List forecastOrderBizNos = getNeedRetryForecastOrdersByRecordRequest.getForecastOrderBizNos();
        Result<List<CreateForecastOrderRecords>> listResult = this.loadListByOrderBizId(LoadListByOrderBizIdRequest.builder().orderBizId(forecastOrderBizNos).start(0).limit(forecastOrderBizNos.size()).build());
        if (CollectionUtils.isEmpty(listResult.getResult())) {
            result.setMessage("记录表数据为空，请核对预报主单号");
            result.setSuccess(false);
            return result;
        }
        log.info("retry create order records" + JSONObject.toJSONString(listResult));
        //过滤处理状态为已完成且分析状态是分析失败的，调用分析接口再次分析
        List<CreateForecastOrderRecords> recordsList = listResult.getResult();
        recordsList.forEach(record -> {
            try {
                log.info("retry one order record"  + JSONObject.toJSONString(record));
                PageResult<List<ForecastOrderSDO>> listPageResult = forecastOrderQueryRepository.pageQuery(ForecastOrderSDO.builder().orderBizId(record.getOrderBizId()).build());
                List<ForecastOrderSDO> content = listPageResult.getContent();
                log.info("retry one order ForecastOrder"  + JSONObject.toJSONString(content));
                if (CreateForecastOrderRecoudStatusSEO.done.getValue().equals(record.getStatus()) && ForecastDealStatusSEO.ANALYSIS_FAILED.getStatus().equals(record.getDealStatus())) {//处理完成且分析失败
                    //更新记录表
                    record.setRetryNum(record.getRetryNum() + 1);
                    record.setGmt_modified(System.currentTimeMillis());
                    record.setStatus(CreateForecastOrderRecoudStatusSEO.Processing.getValue());
                    record.setDealStatus(ForecastDealStatusSEO.ANALYSIS_ING.getStatus());
                    this.updateOneRecord(record);
                    //放入分析队列
                    this.analysisOrderLineAndSendMsg(AnalysisOrderLineAndSendMsgRequest.builder().forecastOrderLineIds(record.getOrderLineBizIds()).build());
                    ForecastOrderOutResponse outResponse = ForecastOrderOutResponse.builder().success(true).message("已重试").referenceNo(CollectionUtils.isEmpty(content) ? "0" : content.get(0).getCustomerReferenceNo()).forecastOrderBizNo(record.getOrderBizId()).build();
                    responseList.add(outResponse);
                } else {//处理完成且分析完成、处理中都无需重试
                    String message = ForecastDealStatusSEO.ANALYSIS_ED.getStatus().equals(record.getDealStatus()) ? "已完成无需重试" : "处理中无需重试";
                    ForecastOrderOutResponse outResponse = ForecastOrderOutResponse.builder().success(true).message(message).referenceNo(CollectionUtils.isEmpty(content) ? "0" : content.get(0).getCustomerReferenceNo()).forecastOrderBizNo(record.getOrderBizId()).build();
                    responseList.add(outResponse);
                }
            } catch (Exception e) {
                log.error("getNeedRetryForecastOrdersByRecord_fail data " + JSON.toJSONString(record));
                log.error("getNeedRetryForecastOrdersByRecord_fail reason " + e);
                //返回结果
                PageResult<List<ForecastOrderSDO>> listPageResult = forecastOrderQueryRepository.pageQuery(ForecastOrderSDO.builder().orderBizId(record.getOrderBizId()).build());
                List<ForecastOrderSDO> content = listPageResult.getContent();
                ForecastOrderOutResponse outResponse = ForecastOrderOutResponse.builder().success(false).message("重试失败").referenceNo(CollectionUtils.isEmpty(content) ? "0" : content.get(0).getCustomerReferenceNo()).forecastOrderBizNo(record.getOrderBizId()).build();
                responseList.add(outResponse);
                //更新记录表
                CreateForecastOrderRecords records = this.loadOneRecord(LoadOneRecordRequest.builder().orderBizId(record.getOrderBizId()).build());
                records.setFailReason(JSON.toJSONString(new JSONObject().put("Exception", "再次分析，放入分析队列失败")));
                records.setGmt_modified(System.currentTimeMillis());
                this.updateOneRecord(records);
            }
        });

        result.setResult(responseList);
        result.setSuccess(Boolean.TRUE);
        result.setTotal(recordsList.size());
        return result;
    }


    /**
     * 说明
     * mq2-consumer-api
     * 步骤1：获取分析批次号，查明细DealLineQueue$loadDealLineQueueList（单个预报单维度），过滤dealStatus=2，≠2（未分析完）的抛回队列
     * 步骤2：已经分析完成的明细集合（单个预报单维度），查batchForecastOrderLineList明细
     * bulbType=1批量确认生成销售单，更新记录表
     * bulbType=2/3,更新记录表
     * 接口一：第四步、第五步
     * 接口二：第三步、第四步
     *
     * @author jc
     * @since 1.0
     */
    @Override
    @ProcessInvoker
    public Result<List<ForecastOrderOutResponse>> saveOrdersUpdateRecords(SaveOrdersUpdateRecordsRequest saveOrdersUpdateRecordsRequest) {
        if (Objects.isNull(saveOrdersUpdateRecordsRequest)) {
            return Result.fail("SYS_ERR_ANY_INVALID_PARAM", "系统异常，消息内容为空");
        }
        String batchNo = saveOrdersUpdateRecordsRequest.getMessage();

        if (StringUtils.isBlank(batchNo)) {
            return Result.fail("SYS_ERR_ANY_INVALID_MSG", "系统异常，项目内容为空");
        }
        log.info("check line status and confirm"  + batchNo);
        LoadDealLineQueueListRequest loadDealLineQueueListRequest = LoadDealLineQueueListRequest.builder().batchNumber(batchNo).build();
        List<DealLineQueue> lineQueueList = dealLineQueueService.loadDealLineQueueList(loadDealLineQueueListRequest).getResult();
        log.info("analysis line queue"  + JSONObject.toJSONString(lineQueueList));
        //dealStatus≠2没都处理完，报错抛回队列
        List<String> forecastLineIds = new ArrayList<>();
        lineQueueList.forEach(dealLineQueue -> {
            if (!ForecastDealStatusSEO.ANALYSIS_ED.getStatus().equals(dealLineQueue.getDealStatus())
                    &&!ForecastDealStatusSEO.ANALYSIS_FAILED.getStatus().equals(dealLineQueue.getDealStatus())) {
                log.error("line has not finish"  + JSONObject.toJSONString(dealLineQueue));
                throw new RuntimeException("子单分析未完成，消息抛回队列");
            }
            forecastLineIds.add(dealLineQueue.getForecastOrderLineId());
        });

        //已分析的预报单明细
        List<ForecastOrderLineSDO> forecastOrderLineSDOS = forecastOrderLineQueryRepository.batchForecastOrderLineList(forecastLineIds);
        log.info("line has complete analysis" + JSONObject.toJSONString(forecastOrderLineSDOS));
        //本条预报单记录(每个批次是一条预报主单)
        CreateForecastOrderRecords record = this.loadOneRecord(LoadOneRecordRequest.builder().orderBizId(forecastOrderLineSDOS.get(0).getMainOrderBizId()).build());
        log.info("forecastOrder analysis complete record" + JSONObject.toJSONString(record));
        // bulbType=1批量确认生成销售单，更新记录表
        // bulbType=2/3,记录失败原因，更新记录表
        boolean isConfirm = true;
        JSONObject filReasonMap = new JSONObject();
        List<String> satisfyForecastLineIds = new ArrayList<>();
        for (ForecastOrderLineSDO forecastOrderLineSDO : forecastOrderLineSDOS) {
            Map feature = forecastOrderLineSDO.getFeatures();
            int bulbType = 0;
            int activityTag = 0;
            if (MapUtils.isNotEmpty(feature)) {

                if (feature.containsKey("bulbType")) {
                    bulbType = (int) feature.get("bulbType");
                }
                if (feature.containsKey("activityTag")) {
                    activityTag = (int) feature.get("activityTag");
                }
            }
            //未完全满足,记录失败原因，更新记录表（更新时间、处理状态、分析状态、失败原因）
            //存在活动冲突 activityTag=1应该阻断流程
            if (!AnalyzeReasonsSEO.TOTALLY_SATISFIED.getBulbType().equals(bulbType)) {
                //整个批次有一条不满足，即批次失败，不确认，只更新记录表
                isConfirm = false;
                filReasonMap.put(forecastOrderLineSDO.getScItemOutCode(), forecastOrderLineSDO.getAnalysisReason());
                log.info("forecastOrder not satisfy completely:"  + JSONObject.toJSONString(forecastOrderLineSDO));
            } else if (1==activityTag){
                isConfirm = false;
                filReasonMap.put(forecastOrderLineSDO.getScItemOutCode(), "活动冲突!");
                log.info("forecastOrder activity conflict:"  + JSONObject.toJSONString(forecastOrderLineSDO));
            }else {//完全满足，收集子单id，更新记录表(更新时间、处理状态、分析状态)
                satisfyForecastLineIds.add(String.valueOf(forecastOrderLineSDO.getId()));
            }
        }

        if (isConfirm) {//确认生成销售单
            log.info("all satisfy preparing confirm create forecastOrder"  + JSONObject.toJSONString(satisfyForecastLineIds));
            ApiContext apiContext = ApiContext.builder().employeeId(TETONGEMPLOYEEID).employeeName(TETONGEMPLOYEENAME).build();
            BatchSaveOrderConfirmRequest confirmRequest = BatchSaveOrderConfirmRequest.builder().apiContext(apiContext).ids(satisfyForecastLineIds).build();
            try {
                BatchSaveOrderConfirmResponse confirmResponse = otsForecastSalesService.batchSaveOrderConfirm(confirmRequest);
                if (Objects.isNull(confirmResponse)){
                    filReasonMap.put("confirmError","确认销售订单失败!");
                    record.setDealStatus(ForecastDealStatusSEO.ANALYSIS_FAILED.getStatus());
                    record.setGmt_modified(System.currentTimeMillis());
                    record.setFailReason(JSONObject.toJSONString(filReasonMap));
                    record.setStatus(CreateForecastOrderRecoudStatusSEO.done.getValue());
                    this.updateOneRecord(record);
                    return Result.success(null);
                }
                if (!confirmResponse.getSuccess()||!(boolean)confirmResponse.getResult()){
                    log.error("spec submit forecast error:mainOrderId:"+forecastOrderLineSDOS.get(0).getMainOrderId()+"error:"+confirmResponse.getMessage());
                    filReasonMap.put("confirmError",confirmResponse.getMessage());
                    record.setDealStatus(ForecastDealStatusSEO.CONFIRM_ING.getStatus());
                    record.setGmt_modified(System.currentTimeMillis());
                    record.setFailReason(JSONObject.toJSONString(filReasonMap));
                    record.setStatus(CreateForecastOrderRecoudStatusSEO.done.getValue());
                    this.updateOneRecord(record);
                    return Result.success(null);
                }

            } catch (Exception e) {
                log.error("spec submit forecast error,mainOrderId:"+forecastOrderLineSDOS.get(0).getMainOrderId()+"error:"+e.getMessage());
                filReasonMap.put("confirmError","确认销售订单失败!");
                record.setDealStatus(ForecastDealStatusSEO.ANALYSIS_FAILED.getStatus());
                record.setGmt_modified(System.currentTimeMillis());
                record.setFailReason(JSONObject.toJSONString(filReasonMap));
                record.setStatus(CreateForecastOrderRecoudStatusSEO.done.getValue());
                this.updateOneRecord(record);
                e.printStackTrace();
                return Result.success(null);
            }
            record.setDealStatus(ForecastDealStatusSEO.ANALYSIS_ED.getStatus());
        } else {
            record.setDealStatus(ForecastDealStatusSEO.ANALYSIS_FAILED.getStatus());
        }
        record.setGmt_modified(System.currentTimeMillis());
        record.setFailReason(JSONObject.toJSONString(filReasonMap));
        record.setStatus(CreateForecastOrderRecoudStatusSEO.done.getValue());
        this.updateOneRecord(record);
        return Result.success(null);
    }


    /**
     * 说明
     * 接收子单ID集合（单个预报单下的所有子单），调用分析方法，并发mq2（batchNo）
     * 接口一：第三步
     * 接口二：第二步
     *
     * @author jc
     * @since 1.0
     */
    @Override
    @ProcessInvoker
    public Object analysisOrderLineAndSendMsg(AnalysisOrderLineAndSendMsgRequest analysisOrderLineAndSendMsgRequest) {

        if (Objects.isNull(analysisOrderLineAndSendMsgRequest)) {
            throw new RuntimeException("系统错误，参数异常！");
        }

        if (CollectionUtils.isEmpty(analysisOrderLineAndSendMsgRequest.getForecastOrderLineIds())) {
            throw new RuntimeException("子单集合分析内容为空！");
        }
        log.info("forecastOrderLine analysis and send confirm msg"  + JSONObject.toJSONString(analysisOrderLineAndSendMsgRequest));

        ApiContext apiContext = ApiContext.builder().employeeId(TETONGEMPLOYEEID).employeeName(TETONGEMPLOYEENAME).build();
        BatchAnalysisOrdersRequest batchAnalysisOrdersRequest = BatchAnalysisOrdersRequest.builder()
                .apiContext(apiContext)
                .ids(analysisOrderLineAndSendMsgRequest.getForecastOrderLineIds())
                .modifierId(TETONGEMPLOYEEID)
                .modifierName(TETONGEMPLOYEENAME)
                .build();
        List<ForecastOrderLineSDO> forecastOrderLineSDOS = forecastOrderLineQueryRepository.batchForecastOrderLineList(analysisOrderLineAndSendMsgRequest.getForecastOrderLineIds());
        if (CollectionUtils.isEmpty(forecastOrderLineSDOS)) {
            throw new RuntimeException("未查到预报单明细，请核对预报单明细id");
        }
        CreateForecastOrderRecords record = this.loadOneRecord(LoadOneRecordRequest.builder().orderBizId(forecastOrderLineSDOS.get(0).getMainOrderBizId()).build());
        log.info("get record data"  + JSONObject.toJSONString(record));
        Result<Boolean> batchAnalysisOrdersResult = forecastOrderWriteService.batchAnalysisOrders(batchAnalysisOrdersRequest);
        log.info("batchAnalysisOrders result"  + JSONObject.toJSONString(batchAnalysisOrdersResult));
        if (batchAnalysisOrdersResult.isSuccess() && batchAnalysisOrdersResult.getResult()) {//放入分析队列成功,发送确认消息
            Boolean isSend = false;
            try {
                isSend = messageService.sendMessage("analysisSpecForecastQueue", "analysisSpecForecast_V2", "analysisSpecForecastTetong", batchAnalysisOrdersResult.getMessage());
                log.info("send confirm msg result"  + isSend);
            } catch (Exception e) {
                log.error("send confirm msg error"  + batchAnalysisOrdersResult.getMessage()  + e.getMessage());
            }
            record = this.loadOneRecord(LoadOneRecordRequest.builder().orderBizId(record.getOrderBizId()).build());
            if (!isSend) {//发送确认消息失败
                record.setFailReason(JSON.toJSONString(new JSONObject().put("Exception", "发送确认生成销售单消息失败")));
                record.setStatus(CreateForecastOrderRecoudStatusSEO.done.getValue());
                record.setDealStatus(ForecastDealStatusSEO.ANALYSIS_FAILED.getStatus());
                record.setGmt_modified(System.currentTimeMillis());
            }
        } else {//放入分析队列失败，更新记录表
            record.setFailReason(JSON.toJSONString(new JSONObject().put("Exception", batchAnalysisOrdersResult.getMessage())));
            record.setStatus(CreateForecastOrderRecoudStatusSEO.done.getValue());
            record.setDealStatus(ForecastDealStatusSEO.ANALYSIS_FAILED.getStatus());
            record.setGmt_modified(System.currentTimeMillis());
        }
        this.updateOneRecord(record);
        return Result.success(null);
    }
}
